import React, { useEffect, useState, useRef } from "react";
import {
  Form,
  Input,
  Button,
  Row,
  Col,
  Switch,
  message,
  Spin,
  Tag
} from "antd";
import { connect } from "dva";
import styles from "./AddTemplate.less";
import {
  // saveMessageTemplate,
  addList,
  updateStatus,
  getDetail
  // getSmsSign
} from "../../services/acceptGroup";
import Receives from "./components/receives";
import { getQueryVariable } from "../../../../utils/utils";

function AddTemplate(props) {
  const {
    form,
    // location: { search },
    userInfo
  } = props;
  // const searchParams = new URLSearchParams(search.substring(1));
  const id = getQueryVariable("id");
  const { getFieldDecorator, setFieldsValue, validateFields } = form;
  const [loading, setloading] = useState(false);
  const [spinning, setSpinning] = useState(false);
  const [receiveVisible, setreceiveVisible] = useState(false);
  const [listOfReceivers, setlistOfReceivers] = useState([]);
  const rangeRef = useRef();

  // 编辑时数据回显
  useEffect(() => {
    if (id) {
      setSpinning(true);
      getDetail({ id, t: Date.now() }).then(res => {
        const { baseReceiveGroupRangeDTOList, ...rest } = res.datas;
        setlistOfReceivers(
          baseReceiveGroupRangeDTOList.map(l => {
            try {
              return { ...l, rangeEntityId: JSON.parse(l.rangeEntityId) };
            } catch (e) {
              return [];
            }
          })
        );
        setFieldsValue({ ...rest, isEnabled: rest.isEnabled === "Y" });
        setSpinning(false);
      });
    }
  }, [id]);

  useEffect(() => {
    setFieldsValue({});
  }, []);

  const handleSubmit = () => {
    validateFields().then((values, errs) => {
      if (errs) return;
      // 计算接受范围数量，不能为零
      if (getReceiveCount() === 0) {
        message.error("接收用户范围不能为空");
        return;
      }
      setloading(true);
      if (id) {
        const params = {
          ...values,
          id,
          isEnabled: values.isEnabled ? "Y" : "N",
          tenantCode: "test",
          baseReceiveGroupRangeAddCmdList: listOfReceivers
            .map(r => {
              if (r.rangeEntityId.length > 0) {
                return {
                  rangeType: r.rangeType,
                  creator: userInfo.userName,
                  rangeEntityId: JSON.stringify(r.rangeEntityId)
                };
              }
              return false;
            })
            .filter(Boolean)
        };
        updateStatus(params).then(res => {
          if (res.success) {
            message.success("操作成功");
            window.history.go(-1);
          } else {
            message.error(res.errMsg);
          }
          setloading(false);
        });
      } else {
        const params = {
          ...values,
          isEnabled: values.isEnabled ? "Y" : "N",
          tenantCode: "test",
          creator: userInfo.userName,
          baseReceiveGroupRangeAddCmdList: listOfReceivers
            .map(r => {
              if (r.rangeEntityId.length > 0) {
                return {
                  rangeType: r.rangeType,
                  creator: userInfo.userName,
                  rangeEntityId: JSON.stringify(r.rangeEntityId)
                };
              }
              return false;
            })
            .filter(Boolean)
        };
        addList(params).then(res => {
          if (res.success) {
            message.success("操作成功");
            window.history.go(-1);
          } else {
            message.error(res.errMsg);
          }
          setloading(false);
        });
      }
    });
  };

  function getReceiveCount() {
    let arr = 0;
    listOfReceivers.forEach(r => {
      r.rangeEntityId.forEach(() => {
        arr += 1;
      });
    });
    return arr;
  }

  // 删除接收组标签
  const onTagDel = (recId, rangeId) => {
    const tempArr = listOfReceivers.map(r => {
      if (r.id === recId) {
        const tempObj = r.rangeEntityId.filter(
          e => Object.keys(e)[0] !== rangeId
        );
        return {
          ...r,
          rangeEntityId: tempObj
        };
      }
      return r;
    });
    setlistOfReceivers(tempArr);
  };
  // 处理接收组，显示弹框
  const onHandleReceives = () => {
    setreceiveVisible(true);
  };
  // 处理接收组，关闭弹框
  const onReceiveClose = () => {
    setreceiveVisible(false);
  };
  // 处理接收组，关闭弹框,接受接收范围参数
  const onReceiveOk = ranges => {
    setlistOfReceivers(ranges);
    setreceiveVisible(false);
  };

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 8 }
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 }
    }
  };

  return (
    <div className={styles.root}>
      <Spin spinning={spinning}>
        <Form {...formItemLayout} style={{ width: 800 }}>
          <Row>
            <Col span={12}>
              <Form.Item label="接收组编码">
                {getFieldDecorator("receiveGroupCode", {
                  rules: [
                    { required: true, message: "请输入接收组编码" }
                    // {
                    //   pattern: /^([a-zA-Z]|[`~!@#$^&*()=|{}':;',[\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？%]){1,30}$/,
                    //   message: "请输入30位以内英文+特殊字符(不允许空格)"
                    // }
                  ]
                })(<Input placeholder="请输入接收组编码" />)}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="接收组名称">
                {getFieldDecorator("receiveGroupName", {
                  rules: [
                    { required: true, message: "请输入接收组名称" }
                    // {
                    //   pattern: /^([a-zA-Z]|[\u4E00-\u9FA3]){1,30}$/,
                    //   message: "请输入30位以内中英文"
                    // }
                  ]
                })(<Input placeholder="请输入接收组名称" />)}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item label="启用">
                {getFieldDecorator("isEnabled", { valuePropName: "checked" })(
                  <Switch checkedChildren="开" unCheckedChildren="关" />
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item label="接收用户范围" required>
                <Button type="primary" onClick={onHandleReceives}>
                  选择
                </Button>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={1}></Col>
            <Col span={23}>
              {listOfReceivers.map((rec, i) =>
                rec.rangeEntityId.map((range, j) => (
                  <Tag
                    style={{ marginBottom: 5 }}
                    key={i * listOfReceivers.length + j}
                    closable
                    visible={true}
                    onClose={() => onTagDel(rec.id, Object.keys(range)[0])}
                  >
                    （{Object.keys(range)[0]}）{range[Object.keys(range)[0]]}
                  </Tag>
                ))
              )}
            </Col>
          </Row>
          <Row>
            <Col span={18}></Col>
            <Col span={6} style={{ textAlign: "right" }}>
              <Button
                style={{ marginRight: 10 }}
                onClick={() => {
                  window.history.go(-1);
                }}
              >
                取消
              </Button>
              <Button
                loading={loading}
                type="primary"
                htmlType="submit"
                onClick={handleSubmit}
              >
                保存
              </Button>
            </Col>
          </Row>
        </Form>
      </Spin>
      {receiveVisible && (
        <Receives
          visible={receiveVisible}
          onClose={onReceiveClose}
          onReceiveOk={onReceiveOk}
          listOfReceivers={listOfReceivers}
          ref={rangeRef}
        />
      )}
    </div>
  );
}

export default Form.create()(
  connect(({ user: { userInfo } }) => ({
    userInfo
  }))(AddTemplate)
);
